import { JSX } from 'react';
import { DicomViewer } from '../../components/DicomViewer';
import { NulDialog, NulCommonOperations, NulFormItem } from '../../components/NulDialog';
import { SelectHistoryDetail } from '../../actions/SelectHistory';
import React from 'react';
import { Box } from '@mui/material';
import moment from 'moment';
import { transformAnalyzeResult } from '../../util/TextTransform';

interface AnalyzeHistoryProps {
  open: boolean;
  onClose: () => void;
  content?: SelectHistoryDetail;
};

function AnalyzeHistory(props: AnalyzeHistoryProps): JSX.Element {
  const { open, onClose, content } = props;

  const [buffer, setBuffer] = React.useState<ArrayBuffer | undefined>(undefined);
  
  React.useEffect(() => {
    if (content !== undefined) {
      const binaryString = window.atob(content.data);
      const bytes = new Uint8Array(binaryString.length);

      for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }

      const buffer = bytes.buffer;
      setBuffer(buffer);
    }
  }, [content]);

  return (
    <NulDialog
      open={open}
      onClose={onClose}
      title='View History'
      operations={
        <NulCommonOperations onPositiveClicked={onClose} onNegativeClicked={onClose} />
      }
    >
      <DicomViewer data={buffer} width='300px' height='300px' />
      <Box height='20px' />
      <NulFormItem hint='Result' necessary={false} component={transformAnalyzeResult(content?.result)} />
      <NulFormItem hint='Time' necessary={false} component={content !== undefined ? moment(new Date(content?.time)).format('YYYY-MM-DD HH:mm:ss') : ''} />
    </NulDialog>
  )
}

export { AnalyzeHistory };